<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row :gutter="30">
        <el-col :span="18">
          <el-input placeholder="请输入内容" v-model="select" clearable>
            <el-button slot="append" icon="el-icon-search">搜索</el-button>
          </el-input>
        </el-col>
        <el-col :span="6" class="btn">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="slot">
            <el-row
              v-for="(item1, index1) in slot.row.children"
              :key="item1.id"
              :class="['bdBottom', 'vCenter', index1 === 0 ? 'bdTop' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(slot.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdTop', 'vCenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(slot.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(slot.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deletRoleById(scope.row)"
            >
              删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="small"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- dialoge区域 -->
    <!-- 添加用户 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName">{{
            editForm.roleName
          }}</el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc">{{
            editForm.roleDesc
          }}</el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="40%"
    >
      <el-tree
        :data="allRightData"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defCheck"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesList,
  addRolesN,
  getRoleMessage,
  editRolesN,
  deleteRole,
} from 'network/aboutPower'
export default {
  name: 'Roles',
  data() {
    return {
      select: '',
      rolesList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      editForm: {},
      // 添加角色规则
      addRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      // 编辑角色规则
      editRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      setRightDialogVisible: false,
      allRightData: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      defCheck: [],
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    getRolesList() {
      getRolesList().then((res) => {
        this.rolesList = res.data
      })
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色
    addRoles() {
      this.$refs.addFormRef.validate((res) => {
        if (!res) return
        else {
          addRolesN(this.addForm).then((res) => {
            if (res.meta.status !== 201) {
              return this.$message.error('添加失败！')
            }
            this.addDialogVisible = false
            this.getRolesList()
            this.$message.success('添加成功')
          })
        }
      })
    },
    // 展示编辑角色信息
    showEditDialog(userInfo) {
      this.editDialogVisible = true
      getRoleMessage(userInfo.id).then((res) => {
        if (res.meta.status !== 200) return
        this.editForm = res.data
      })
    },
    // 编辑角色
    editRoles() {
      this.$refs.editFormRef.validate((res) => {
        if (!res) return
        editRolesN(this.editForm).then((res) => {
          if (res.meta.status !== 200) {
            return this.$message.error('修改失败！')
          }
          this.editDialogVisible = false
          this.getRolesList()
          this.$message.success('修改成功')
        })
      })
    },
    // 删除角色
    deletRoleById(userInfo) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteRole(userInfo.id).then((res) => {
            if (res.meta.status !== 200) {
              return this.$message.error(res.meta.msg)
            }
            this.getRolesList()
            this.$message.success(res.meta.msg)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 删除权限
    removeRightById(role, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败！')
          }
          role.children = res.data
          this.$message.success('删除权限成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      this.allRightData = res.data
      this.defCheck = []
      this.getLeafKeys(role, this.defCheck)
      this.setRightDialogVisible = true
    },
    // 给权限树默认选择数组添加id值
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 添加权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const rids = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('设置权限失败！')
      }
      this.$message.success('设置权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
  },
}
</script>

<style scoped>
.el-col-18 {
  width: 40%;
}
.btn {
  float: right;
}
.el-tag {
  margin: 10px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.vCenter {
  display: flex;
  align-items: center;
}
</style>
